package demo1;

import java.util.Objects;

class Money implements Cloneable{//深拷贝，class Money浅拷贝//这里就要添上implements Cloneable
    public  double m = 19.9;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();//深拷贝如果要克隆，就要写这个，重写克隆
    }
}
class Person implements Cloneable{//当我们自己写的类型想要实现吃，clone时一定要给他写一个Cloneable的接口
    public String name;
    public int age;

    public Money money = new Money();
    public Person (String name,int age){
        this.name = name;
        this.age = age;

    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {//可能会被抛出异常/这个异常叫做，不支持克隆异常编译时期的异常
        Person tmp = (Person)super.clone();//深拷贝
        //return super.clone();//这里面在clone Person，并未clone Money//浅拷贝
        tmp.money = (Money) this.money.clone();//深拷贝
        return tmp;//深拷贝
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age && Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    /*@Override
    public boolean equals(Object obj) {
        Person tm =  (Person)obj;
        return this.name.equals(tm.name)&&this.age == tm.age;
    }*/
}

public class Test2 {
    public static void main(String[] args) {
        Person person1 = new Person("张三",12);
        Person person2 = new Person("张三",12);
        System.out.println(person1.equals(person1));

    }
    public static void main2(String[] args) throws CloneNotSupportedException {

        Person person1 = new Person("张三",12);
        Person person2 =  (Person)person1.clone();
        System.out.println(person1.money.m);
        System.out.println(person2.money.m);
        System.out.println("=============");
        person1.money.m = 199.99;
        System.out.println(person1.money.m);
        System.out.println(person2.money.m);

    }
    public static void main1(String[] args) throws CloneNotSupportedException {//刚加上这个的时候还是会报错，

        Person person1 = new Person("张三",12);
        //Person person2 = person1.clone();//报错的原因： 为什么会报错：clone方法的返回值是Object，因此，这里把父类给子类一定会报错
        //所以我们在这里强转一下
        Person person2 =  (Person)person1.clone();
        System.out.println(person1.name);
        System.out.println(person2.name);//还是会异常
        //当我们自己写的类型想要实现吃，clone时一定要给他写一个Cloneable的接口
    }
}
